<script setup>
import { onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/useUserStore";
import { updateUserInfoAPI } from "@/api/user";

const userStore = useUserStore();
const userInfo = ref({ id: "", username: "", nickname: "", email: "" });
const rules = {
  nickname: [
    { required: true, message: "请输入用户昵称", trigger: "blur" },
    {
      pattern: /^\S{2,10}$/,
      message: "昵称必须是2-10位的非空字符串",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入用户邮箱", trigger: "blur" },
    { type: "email", message: "邮箱格式不正确", trigger: "blur" },
  ],
};

// 获取信息
const getUserInfo = () => {
  userInfo.value.id = userStore.account.id;
  userInfo.value.username = userStore.account.username;
  userInfo.value.nickname = userStore.account.nickname;
  userInfo.value.email = userStore.account.email;
};

const fromRef = ref();
const submitForm = async formEl => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      updateUserInfo();
    } else {
      for (const key in fields) {
        ElMessage({ type: "error", message: fields[key][0].message });
      }
    }
  });
};

const updateUserInfo = async () => {
  const res = await updateUserInfoAPI(userInfo.value);
  if (res.code === 0) {
    userStore.setAccount();
    return ElMessage({ type: "success", message: "修改成功" });
  }
  return ElMessage({ type: "error", message: res.message });
};

onMounted(() => {
  getUserInfo();
});
</script>
<template>
  <el-card class="page-container" v-if="userStore.account">
    <template #header>
      <div class="header">
        <span>基本资料</span>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <el-form :model="userInfo" :rules="rules" label-width="100px" size="large" ref="fromRef">
          <el-form-item label="登录名称" title="需要修改请联系管理">
            <el-input v-model="userInfo.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="userInfo.nickname"></el-input>
          </el-form-item>
          <el-form-item label="用户邮箱" prop="email">
            <el-input v-model="userInfo.email"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(fromRef)">提交修改</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>
